from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, GenericAPIView, CreateAPIView, UpdateAPIView, DestroyAPIView

from areas.serializers import AreasSerializer, AddressesSerializer, TitleSerializer
from .models import Area
from users.models import Address
from rest_framework_extensions.cache.mixins import CacheResponseMixin


# Create your views here.
class AreasView(CacheResponseMixin, ListAPIView):
    serializer_class = AreasSerializer
    queryset = Area.objects.filter(parent__isnull=True)
    # def get(self, request):
    #     names_list = []
    #     names = Area.objects.filter(parent__isnull=True)
    #     for name in names:
    #         names_list.append({'id': name.id, 'name': name})
    #     return Response({'id':518000,'name':'北京市'})


class AreaView(CacheResponseMixin, ListAPIView):
    serializer_class = AreasSerializer

    def get_queryset(self):
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


class AddressesView(CreateAPIView, ListAPIView):
    serializer_class = AddressesSerializer

    # queryset =Address.objects.filter(is_deleted=False)
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response({'addresses':serializer.data})
    # def get(self,request):
    #     serializer = self.get_serializer(data=request.data)


class TitleView(UpdateAPIView):
    serializer_class = TitleSerializer
    queryset = Address.objects.all()


class AddressUpdateView(UpdateAPIView, DestroyAPIView):
    serializer_class = AddressesSerializer
    queryset = Address.objects.all()


# class AddressDeleteView(DestroyAPIView):
#     serializer_class = AddressesSerializer
#     queryset = Address.objects.all()


class DefaultAddressView(UpdateAPIView):
    serializer_class = AddressesSerializer
